const Taf = require('@taf/taf-rpc').client;
const News = require('./BytesQueueProxy').News;

function newsHelper() {
    let strPrx = global.CONFIG.proxy.BytesQueueObj;
    if (!strPrx) {
        strPrx = 'News.CrawlerQueueServer.BytesQueueObj';
    }

    if (!process.env.TAF_CONFIG) { // 非taf环境下，加上ip
        strPrx += '@tcp -h 172.16.8.125 -t 60000 -p 8888';
    }
    console.log('news-strPrx------------------------------------------', strPrx);

    let rpcObj = Taf.stringToProxy(News.BytesQueueProxy, strPrx);
    rpcObj.setTimeout(2000);

    return {
        getQueueLength(queueName) {
            return new Promise((resolve, reject) => {
                rpcObj.lenBytes(queueName).then((rsp) => {
                    if (rsp.response.return === 0) {
                        let { queueLength } = rsp.response.arguments;
                        resolve(queueLength);
                    } else {
                        reject(JSON.stringify(rsp));
                    }
                }).catch((err) => {
                    let msg = err;
                    if (err && err.response && err.response.error) {
                        msg = err.response.error;
                    }
                    reject(new Error(`getQueueLength Error: ${JSON.stringify(msg)}`));
                });
            });
        }
    };
}
module.exports = newsHelper;
